<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: CreateOrder.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\duobao;

use app\api\model\dao\DuoBao;
use app\api\model\dao\DuoBaoCart;
use app\api\model\dao\IssuesNumber;
use app\api\model\dao\Goods;
use app\api\model\dao\OrderInfo;
use app\api\model\dao\GoodsSpec;
use app\api\model\dao\OrderGoods;
use app\api\model\dao\UserAddress;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;
use think\Log;
use app\library\Flag;
use Alipay\Alipaynotify;

class CreateDuobaoOrder extends PageBase
{
    private $objOrderInfo;
    private $objOrderGoods;
    private $objUserAddress;
    private $objGoodsSpec;
    private $objGoods;
    private $objDuoBaoCart;
    private $objIssuesNumber;
    private $objDuobao;

    public function __construct()
    {
        parent::__construct();
        $this->objOrderInfo = new OrderInfo();
        $this->objOrderGoods = new OrderGoods();
        $this->objGoodsSpec = new GoodsSpec();
        $this->objUserAddress = new UserAddress();
        $this->objIssuesNumber = new IssuesNumber();
        $this->objGoods = new Goods();
        $this->objGoodsSpec = new GoodsSpec();
        $this->objDuoBaoCart = new DuoBaoCart();
        $this->objDuobao = new DuoBao();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'issues_no' => 'require',
            'number' => 'require',
            'pay_id' => 'require',
        ];
        $msg = [
            'issues_no.require' => '夺宝期号',
            'number.require' => '夺宝数量必填',
            'pay_id.require' => '支付方式必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }

        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        $user_id = $this->user_id;
        $issues_no = $param['issues_no'];

        $arrConds = [
            'issues_no' => $issues_no,
        ];
        $ret = $this->objIssuesNumber->getIssuesNumberByCond($arrConds);
        $goods_id = $ret[0]['goods_id'];
        $goods_spec_id = $ret[0]['goods_spec_id'];

        $this->objOrderInfo->db(true)->startTrans();

        $goods_amount_sum = 0;
        $order_amount_sum = 0;

        // 计算其它

        // 订单信息
        $param['best_time'] = time();
        $param['goods_amount'] = $goods_amount_sum;
        $order_amount_sum = $goods_amount_sum;
        $param['order_amount'] = $order_amount_sum;
        $param['discount'] = 0;

        $order_id = $this->objOrderInfo->generalOrderid();
        $order['order_id'] = $order_id;
        $order['order_type'] = 1;
        $order['user_id'] = $user_id;
        $order['user_name'] = $this->user_name;
        $order['order_status'] = Flag::ORDER_STATUS_WKJ;
        $order['shipping_status'] = Flag::SHIPPING_STATUS_NOT_SENDING;
        $order['pay_status'] = Flag::PAY_STATUS_NOT;
        $order['consignee'] = '';
        $order['country'] = 0;
        $order['province'] = 0;
        $order['city'] = 0;
        $order['district'] = 0;
        $order['address'] = 0;
        $order['zipcode'] = 0;
        $order['tel'] = 0;
        $order['mobile'] = 0;
        $order['best_time'] = 0;
        $order['goods_amount'] = $param['number'];
        $order['order_amount'] =  $param['number'];
        $order['discount'] = 0;
        $order['pay_id'] = $param['pay_id'];
        $order['add_time'] = time();
        $order['issues_no'] = $issues_no;
        $ret = $this->objOrderInfo->addOrder($order);
        // 计算订单金额

        $goods = $this->objGoods->getGoods($goods_id);
        $goods_spec = $this->objGoodsSpec->getGoodsSpecByid($goods_spec_id);
        $save = array();
        $save['order_id'] = $order_id;
        $save['goods_id'] = $goods_id;
        $save['goods_name'] = $goods[0]['goods_name'];
        $save['goods_number'] = 0;
        $save['market_price'] = $goods[0]['market_price'];
        $save['shop_price'] = $goods[0]['shop_price'];
        $save['goods_spec_id'] = !empty($goods_spec[0]['goods_spec_id']) ? $goods_spec[0]['goods_spec_id'] : 0;
        $save['goods_spec_name'] = !empty($goods_spec[0]['spec_name']) ? $goods_spec[0]['spec_name'] : '';
        $save['is_hot'] = $goods[0]['is_hot'];
        $save['is_new'] = $goods[0]['is_new'];
        $save['is_promote'] = $goods[0]['is_promote'];
        $save['is_free_shipping'] = $goods[0]['is_free_shipping'];
        $save['is_special_packing'] = $goods[0]['is_special_packing'];
        $saves[] = $save;
        $this->objDuoBaoCart->deleteCart($user_id, $goods_id, $issues_no);
        $ret = $this->objOrderGoods->addOrderGoods($saves);

        $datas = array();
        for ($i = 0; $i < $param['number']; $i++) {
            $data = array();
            $data['issues_no'] = $issues_no;
            $data['user_id'] = $user_id;
            $data['goods_id'] = $goods_id;
            $data['create_time'] = time();
            $datas[] = $data;
        }
        if (!empty($datas)) {
            $ret = $this->objDuobao->addMultiDuoBao($datas);
        }

        if ($order_id && $ret) {
            $this->objOrderInfo->db(true)->commit();
        } else {
            $this->objOrderInfo->db(true)->rollback();
            Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
            return $this->getRes(Error::ERR_SYS);
        }

        $param['order_id'] = $order_id;
        $this->payBefore($param);

    //    return $this->getRes();
    }

    public function payBefore($param)
    {
        require_once EXTEND_PATH . 'Alipay/AopClient.php';
        require_once EXTEND_PATH . 'Alipay/request/AlipayTradeAppPayRequest.php';

        $alipay_config = config('alipay_config');

        $order_id = $param['order_id'];

        $out_trade_no = $order_id;
        $total_fee = 0;   //付款金额

        $order = $this->objOrderInfo->getOrderInfo($order_id);
        $order_amount = $order['order_amount'];
        $shipping_fee = $order['shipping_fee'];
        $total_fee = $order_amount + $shipping_fee;


        $aop = new \AopClient;
        $aop->gatewayUrl = $alipay_config['gateway_url'];
        $aop->appId = $alipay_config['app_id'];
        $aop->rsaPrivateKey = $alipay_config['private_key'];
        $aop->format = $alipay_config['format'];
        $aop->charset = $alipay_config['charset'];
        $aop->signType = $alipay_config['sign_type'];
        $aop->alipayrsaPublicKey = $alipay_config['alipay_public_key'];
        $request = new \AlipayTradeAppPayRequest();

        $biz_arr = [];
        $biz_arr['body'] = '测试';
        $biz_arr['subject'] = '温社支付测试';
        $biz_arr['out_trade_no'] = '' . $out_trade_no;
        $biz_arr['timeout_express'] = '30m';
        $biz_arr['total_amount'] = '' . $total_fee;
        $biz_arr['total_amount'] = '0.01';
        $biz_arr['product_code'] = 'QUICK_MSECURITY_PAY';

        $bizcontent = json_encode($biz_arr);

        $request->setNotifyUrl($alipay_config['notify_url']);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request);
        echo $response;
        exit;
    }
}
